package com.groupbuying.currency.producer.controller;

import com.aliyun.openservices.shade.com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.aliyun.openservices.shade.com.alibaba.rocketmq.client.producer.MessageQueueSelector;
import com.aliyun.openservices.shade.com.alibaba.rocketmq.client.producer.SendResult;
import com.aliyun.openservices.shade.com.alibaba.rocketmq.client.producer.SendStatus;
import com.aliyun.openservices.shade.com.alibaba.rocketmq.common.message.Message;
import com.aliyun.openservices.shade.com.alibaba.rocketmq.common.message.MessageQueue;

import java.util.List;
import java.util.UUID;

public class ProducerqMq {
    private DefaultMQProducer sender;

    protected  String nameServer;

    protected  String groupName;

    protected  String topics;

    public void   init(){

        sender = new DefaultMQProducer(groupName);
        sender.setNamesrvAddr(nameServer);
        sender.setInstanceName(UUID.randomUUID().toString());

        try{
            sender.start();
        }catch (Exception e){
            e.printStackTrace();
        }


    }
    public ProducerqMq(String nameServer, String groupName, String topics)
    {

        this.nameServer = nameServer;
        this.groupName = groupName;
        this.topics = topics;

    }

    public void send(Message message, int i)
    {

        message.setTopic(topics);
        message.setKeys(String.valueOf(i));

        // 实现message接收的顺序和插队
        if (i != 5)
        {
            message.setDelayTimeLevel(2);
        }

        int dex = i % 100;
        try
        {
            // 为了保证顺序消费，将消息定义在一个MessageQueue中
            SendResult result = sender.send(message, new MessageQueueSelector()
            {

                public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg)
                {
                    int id = (Integer) arg;
                    int index = id % mqs.size();
                    return mqs.get(index);
                }

            }, dex);
            SendStatus status = result.getSendStatus();

            String info = "第"
                    + i
                    + "次发送的messageId = "
                    + result.getMsgId()
                    + ", "
                    + "status = "
                    + status
                    + " MessageQueue id = "
                    + result.getMessageQueue().getQueueId();

            System.out.println(info);


        }
        catch (Exception e)
        {

            e.printStackTrace();
        }
    }


}
